<template>
  <el-card>
    <div slot="header">
      <h3>区域标准加价率-编辑</h3>
    </div>
    <div class="page-body" v-loading="pageLoading">
      <!-- 发起原因输入框 -->
      <LaunchReasonInput required :reason.sync="launchReason" />
      <el-divider />
      <div class="header-action-bar">
        <div class="select-area-wrap">
          <div v-loading="areaSelect.loading">
            <span>业务区域：</span>
              <el-select
                clearable
                placeholder="请选择业务区域"
                :disabled="areaSelect.disabled"
                v-model="areaSelect.code"
              >
                <el-option
                  v-for="item in areaSelect.options"
                  :key="item.areaCode"
                  :label="item.areaName"
                  :value="item.areaCode"
                />
              </el-select>
          </div>
          <div>
            <span>操作类型：</span>
            <el-select
              clearable
              placeholder="请选择操作类型"
              :disabled="optSelect.disabled"
              v-model="optSelect.code"
            >
              <el-option
                v-for="item in optSelect.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
        <!-- 按钮操作栏 -->
        <BtnRender :render="renderBtnsBar" />
      </div>
      <el-row>
      <SkusTable
        :defaultMinWidth="100"
        :loading="TableInfo.loading"
        :columns="TableInfo.columns"
        :dataSource="TableInfo.list"
        @handleCancelSelect="handleRemoveRow"
      />
    </el-row>
    </div>
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import { TableInfo, openConfirmError, openConfirmTips } from '@/utils/getUtils';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { MAX_EDIT_LIMITS, EDIT_TABLE_COLUMNS, VIEW_TABLE_COLUMNS } from './constants/edit';
import { COMMIT_TYPES, AREA_EDIT_OPT_OPTIONS, getMessageColumns } from '@/constants/markupRate';
import {
  importProductMarkupRateDataUrl,
  commitProductMarkupRateRecordService,
  getSaleAreaService
} from '@/api/finance/salePriceManage/areaMarkupRate';
import {
  processProductMarkupRateTodoRecordDetailService
} from '@/api/finance/salePriceManage/markupRateChangeNotice';
export default {
  components: {
    BtnRender,
    SkusTable,
    LaunchReasonInput
  },
  data () {
    return {
      launchReason: '', // 发起原因
      TableInfo: new TableInfo({ columns: EDIT_TABLE_COLUMNS }),
      btnLoading: {
        export: false,
        submit: false
      },
      isIgnoreTipMsg: false, // 是否忽略异常范围提示（首次提交不忽略，页面存在有异常范围的需业务确认，再次提交时候可忽略直接生成单据）
      areaSelect: { // 业务区域下拉
        code: '',
        options: [],
        loading: false,
        disabled: false // 指导加价率变更通知-去处理跳入此页面时，不可操作业务区域下拉
      },
      optSelect: { // 操作类型下拉
        code: '',
        options: AREA_EDIT_OPT_OPTIONS,
        disabled: false // 指导加价率变更通知-去处理跳入此页面时，不可操作操作类型下拉
      },
      todoRecordNo: '', // 代办单据号
      pageLoading: false // 页面loading
    }
  },
  created () {
    this.setAreaSelectOptions()
  },
  mounted () {
    this.setDetailsByTodoRecordNo()
    this.updateTableColumns()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const redirectBtn = {
        label: '导出数据源',
        method: this.handleExportDataSource
      }
      const importBtn = {
        label: '导入',
        action: importProductMarkupRateDataUrl,
        methods: { handleUploadSuccess: this.handleUploadSuccess },
        isImport: true,
        loadingFn: this.TableInfo.setLoading,
        data: { commitType: COMMIT_TYPES.Area, areaCode: this.areaSelect.code }
      }
      const submitBtn = {
        label: '提交',
        method: this.handleSubmit,
        disabled: this.TableInfo.isNullList(),
        loading: this.btnLoading.submit
      }
      const gobackBtn = { label: '返回', method: this.handleGoBack, type: 'default' }
      const btnBars = [gobackBtn, redirectBtn, importBtn, submitBtn]
      return getListPageBtnsBar(h, btnBars, null, 'end')
    },
    // 删除
    handleRemoveRow ({ index }) {
      this.TableInfo.removeList(index)
    },
    // 返回
    handleGoBack () {
      this.$router.push({ name: 'areaMarkupRateList' })
    },
    // 导出数据源
    handleExportDataSource () {
      const { href } = this.$router.resolve({ name: 'areaMarkupRateList' })
      window.open(href, '_blank')
    },
    // 导入成功
    handleUploadSuccess (res) {
      if (res?.retData) this.TableInfo.setList(res.retData)
      this.updateTableColumns()
    },
    // 提交
    async handleSubmit (isIgnoreTipMsg = false) {
      if (!this.areaSelect.code) return this.$message.warning('请选择业务区域')
      if (!this.optSelect.code) return this.$message.warning('请选择操作类型')
      if (!this.launchReason) return this.$message.warning('发起原因不能为空')
      const data = {
        commitProductMarkupRateRecordDetailParams: this.TableInfo.list,
        isIgnoreTipMsg, // 是否忽略异常范围提示（点击提交不忽略，页面存在有异常范围的需业务确认，点击仍要提交时候可忽略直接生成单据）
        commitType: COMMIT_TYPES.Area,
        opeType: this.optSelect.code,
        areaCode: this.areaSelect.code,
        launchReason: this.launchReason,
        todoRecordNo: this.todoRecordNo, // 通知待办-去修改区域加价率单据时候需指定
      }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await commitProductMarkupRateRecordService(data, loadingFn)
      if (res?.retData) this.executeSubmitedTask(res.retData)
    },
    // 执行提交后的回调任务
    executeSubmitedTask (retData) {
      const processSetInfo = () => {
        this.TableInfo.setColumns([...getMessageColumns(retData), ...this.TableInfo.columns])
        this.TableInfo.setList(retData.commitProductMarkupRateRecordDetailVos)
      }
      const processTipSubmit = () => { this.handleSubmit(true) } // 仍要提交执行回调
      if (retData.hasErrorData) return openConfirmError(processSetInfo) // 提交有错误
      if (retData.hasTipMsg) return openConfirmTips(processTipSubmit, processSetInfo) // 提交有异常
      // 提交成功
      this.$message.success('提交成功')
      this.handleGoBack()
    },
    // 设置业务区域下拉集合
    async setAreaSelectOptions () {
      const loadingFn = state => { this.areaSelect.loading = state }
      const res = await getSaleAreaService({}, loadingFn)
      if (res?.retData) this.areaSelect.options = res.retData
    },
    // 设置表格数据根据代办单号查询详情
    async setDetailsByTodoRecordNo () {
      this.todoRecordNo = this.$route?.query?.todoRecordNo
      if (!this.todoRecordNo) return false
      const data = { recordNo: this.todoRecordNo }
      const loadingFn = state => { this.pageLoading = state }
      const res = await processProductMarkupRateTodoRecordDetailService(data, loadingFn)
      if (res?.retData) {
        this.TableInfo.setList(res.retData?.commitProductMarkupRateRecordDetailVos)
        this.areaSelect.code = res.retData.areaCode
        this.areaSelect.disabled = true
        this.optSelect.code = res.retData.opeType
        this.optSelect.disabled = true
      }
    },
    // 更新表格表列
    updateTableColumns () {
      const isExceedLimits = this.TableInfo.list.length > MAX_EDIT_LIMITS
      const columns = isExceedLimits ? VIEW_TABLE_COLUMNS : EDIT_TABLE_COLUMNS
      this.TableInfo.setColumns(columns)
      if (isExceedLimits) {
        this.$message.warning('可编辑数量为100，超过此限制请在Excel中维护')
      }
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-divider--horizontal {
  margin: 10px 0;
}
.header-action-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .select-area-wrap {
    display: flex;
    align-items: center;
    div:not(:first-of-type) {
      margin-left: 10px;
    }
  }
}
</style>
